<template>
    <div>
        <Button type="primary" ghost icon="md-add" @click="handleOpenCreate">添加角色组</Button>
        <Button @click="handleDeleteMultiple" type="error" ghost icon="md-trash" class="ivu-ml-8"
                v-show="selectedRoleGroupData.length">批量删除
        </Button>
        <div class="ivu-inline-block ivu-fr">
            <Dropdown @on-click="handleChangeTableSize" trigger="click">
                <Tooltip class="ivu-ml" content="密度" placement="top">
                    <i-link>
                        <Icon type="md-list"/>
                    </i-link>
                </Tooltip>
                <DropdownMenu slot="list">
                    <DropdownItem name="default" :selected="tableSize === 'default'">默认</DropdownItem>
                    <DropdownItem name="large" :selected="tableSize === 'large'">宽松</DropdownItem>
                    <DropdownItem name="small" :selected="tableSize === 'small'">紧凑</DropdownItem>
                </DropdownMenu>
            </Dropdown>
            <Tooltip class="ivu-ml" :content="tableFullscreen ? '退出全屏' : '全屏'" placement="top">
                <i-link @click.native="handleFullscreen">
                    <Icon :custom="tableFullscreen ? 'i-icon i-icon-exit-full-screen' : 'i-icon i-icon-full-screen'"/>
                </i-link>
            </Tooltip>
            <Tooltip class="ivu-ml" content="刷新" placement="top">
                <i-link @click.native="handleRefresh">
                    <Icon custom="i-icon i-icon-refresh"/>
                </i-link>
            </Tooltip>
            <Dropdown trigger="click">
                <Tooltip class="ivu-ml" content="列设置" placement="top">
                    <i-link>
                        <Icon type="md-options"/>
                    </i-link>
                </Tooltip>
                <DropdownMenu slot="list">
                    <div class="ivu-p-8">列展示</div>
                    <Divider size="small" class="ivu-mt-8 ivu-mb-8"/>
                    <template v-for="item in columns">
                        <li class="ivu-dropdown-item" :key="item.title" v-if="item.title"
                            @click="item.show = !item.show">
                            <Checkbox v-model="item.show"></Checkbox>
                            <span>{{ item.title }}</span>
                        </li>
                    </template>
                </DropdownMenu>
            </Dropdown>
        </div>
        <Table
            ref="table"
            :columns="tableColumns"
            :data="list"
            :loading="loading"
            :size="tableSize"
            class="ivu-mt"
            @on-sort-change="handleSortChange"
            @on-select="handleSelect"
            @on-select-cancel="handleSelectCancel"
            @on-select-all="handleSelectAll"
            @on-select-all-cancel="handleClearSelect">
            <template slot-scope="{ row }" slot="system">
                {{ getSystemNameBy(row.systemId) }}
            </template>
            <template slot-scope="{ row }" slot="action">
                <div @click.stop.prevent>
                    <a type="text" @click="handleOpenRole(row.id)">授权</a>
                    <Divider type="vertical"/>
                    <a type="text" @click="handleEdit(row.id)">编辑</a>
                    <Divider type="vertical"/>
                    <a type="text" @click="handleDelete(row.id)">删除</a>
                </div>
            </template>
        </Table>
        <div class="ivu-mt ivu-text-center">
            <Page
                :total="pageNation.total"
                :page-size-opts="pageSizeOpts"
                :current.sync="pageNation.pageNumber"
                show-total
                show-sizer
                show-elevator
                :page-size="pageNation.pageSize"
                @on-change="handleChangePage"
                @on-page-size-change="handleChangePageSize"
            />
        </div>
        <Drawer
            :styles="drawer.styles"
            v-model="drawer.show"
            :title="drawer.type === 'edit' ? '编辑角色组' : '添加角色组'"
            :before-close="handleCloseEdit"
            :transfer="false"
            width="360">
            <Form
                v-if="roleGroupInfo && roleGroupInfoReady"
                ref="roleGroupInfoForm"
                :model="roleGroupInfo"
                :rules="roleGroupInfoRules"
                label-position="top"
                label-colon
                hide-required-mark>
                <FormItem prop="rolegpName" label="角色组名称">
                    <Input v-model="roleGroupInfo.rolegpName" placeholder="请输入角色组名称，必填"/>
                </FormItem>
                <FormItem prop="rolegpCode" label="角色组编码">
                    <Input v-model="roleGroupInfo.rolegpCode" placeholder="请输入角色组编码，必填"/>
                </FormItem>
                <FormItem prop="rolegpDescrib" label="角色组描述">
                    <Input v-model="roleGroupInfo.rolegpDescrib" placeholder="角色组描述"/>
                </FormItem>
            </Form>
            <div class="page-sys-role-drawer-footer" v-if="drawer.type === 'edit'">
                <Button type="primary" @click="handleSubmitEdit" :loading="submitting">提交</Button>
            </div>
            <div class="page-sys-role-drawer-footer" v-if="drawer.type === 'new'">
                <Button type="primary" @click="handleSubmitNew" :loading="submitting">提交</Button>
            </div>
        </Drawer>
        <Modal v-model="modal.show" :title="roleGroupInfo ? '分配 ' + roleGroupInfo.rolegpName + ' 的角色组权限' : ''"
               :transfer="false" :styles="{top: modalTop+'px',width:'800px'}">
            <template>
                <tableRoleList ref="tableRole" :selectedRoleIds="selectedRoleIds"></tableRoleList>
                <div slot="footer">
                    <Button type="primary" :loading="submitting" @click="handleSubmitPermission">提交</Button>
                </div>
            </template>
        </Modal>
    </div>
</template>
<script>
import {cloneDeep} from 'lodash';
import tableRoleList from './table-role-list.vue';
export default {
    components: {tableRoleList},
    data() {
        return {
            columns: [
                {type: 'selection', minWidth: 60, align: 'center', show: true},
                {title: 'ID', key: 'id', minWidth: 140, show: false},
                {title: '角色组名称', key: 'rolegpName', minWidth: 140, show: true},
                {title: '角色组编码', key: 'rolegpCode', minWidth: 140, show: true},
                {title: '角色组描述', key: 'rolegpDescrib', minWidth: 140, show: true},
                {title: '创建时间', key: 'createTime', minWidth: 200, show: true},
                {title: '更新时间', key: 'updateTime', minWidth: 200, show: true},
                {title: '操作', key: 'action', slot: 'action', minWidth: 200, align: 'center', fixed: 'right', show: true}
            ],
            loading: false,
            list: [],
            selectedRoleGroupData: [],
            sortType: 'normal', // 当前排序类型，可选值为：normal（默认） || asc（升序）|| desc（降序）,
            sortKey: '', // 排序列的 key
            tableSize: 'default',
            tableFullscreen: false,
            drawer: {
                show: false,
                type: 'edit', // edit || new
                styles: {
                    height: 'calc(100% - 55px)',
                    overflow: 'auto',
                    paddingBottom: '53px',
                    position: 'static'
                }
            },
            roleGroupInfo: null,
            roleGroupInfoRules: {
                name: [
                    {required: true, message: '请输入角色组名称', trigger: 'blur'}
                ]
            },
            roleGroupInfoString: '',
            roleGroupInfoReady: true,
            submitting: false,
            modal: {
                show: false
            },
            pageSizeOpts: [10, 30, 50, 100],
            pageNation: {total: 0, pageSize: 10, pageNumber: 1},
            modalTop: 200,
            modalHeight: 0,
            selectedRoleIds: [],
            rolegpParam: {},
        }
    },
    computed: {
        // 动态设置列
        tableColumns() {
            const columns = [...this.columns];
            return columns.filter(item => item.show);
        },
        lang () {
            return {
                'en-US': {
                    cancel: 'cancel',
                    confirmDelete: 'confirm delete?',
                    confirm: 'confirm'
                },
                'zh-CN': {
                    cancel: '取消',
                    confirmDelete: '确认删除？',
                    confirm: '确认'
                }
            }[this.G_Locale]
        }
    },
    methods: {
        //窗体监听方法
        initElementHeight() {
            //然后监听window的resize事件
            const _this = this;
            _this.calcElementHeight(_this);
            window.onresize = function temp() {
                _this.calcElementHeight(_this);
            };
        },
        calcElementHeight(_this) {
            _this.$nextTick(() => {
                this.modalHeight = document.documentElement.clientHeight - this.modalTop * 2 - 80;
            });
        },
        //获取角色组列信息
        getData() {
            if (this.loading) return;
            this.loading = true;
            // 下面的 params 是获取的表单查询参数
            this.pageNation.total = 0;
            this.list = [];
            let condition = "";
            const params = this.$parent.$parent.$refs.form.data;
            if (params.rolegpName != null && params.rolegpName != "") {
                condition += "rolegpName like '" + params.rolegpName + "'";
            }

            if (params.rolegpCode != null && params.rolegpCode != "") {
                condition += "rolegpCode like '" + params.rolegpCode + "'";
            }

            this.$api.RoleGroup.queryByPage(this.pageNation.pageNumber,this.pageNation.pageSize, {condition}).then(res => {
                this.list = cloneDeep(res.records);
                this.pageNation.total = res.recordCount;
                this.pageNation.pageNumber = res.pageNumber;
                this.pageNation.pageSize = res.pageSize;
            }).finally(()=>{
                this.loading = false;
            });
        },
        // 改变表格尺寸
        handleChangeTableSize(size) {
            this.tableSize = size;
        },
        // 表格全屏
        handleFullscreen() {
            this.tableFullscreen = !this.tableFullscreen;
            this.$emit('on-fullscreen', this.tableFullscreen);
        },
        // 刷新表格数据
        handleRefresh() {
            this.getData();
        },
        // 切换页码
        handleChangePage(page) {
            this.pageNation.pageNumber = page;
            this.getData();
        },
        // 切换每页条数
        handleChangePageSize(size) {
            this.pageNation.pageNumber = 1;
            this.pageNation.pageSize = size;
            this.getData();
        },
        // 排序
        handleSortChange({key, order}) {
            this.pageNation.pageNumber = 1;
            this.sortType = order;
            this.sortKey = key;
            this.getData();
        },
        // 选中一项，将数据添加至已选项中
        handleSelect(selection, row) {
            this.selectedRoleGroupData.push(row);
        },
        // 取消选中一项，将取消的数据从已选项中删除
        handleSelectCancel(selection, row) {
            const index = this.selectedRoleGroupData.findIndex(item => item.id === row.id);
            this.selectedRoleGroupData.splice(index, 1);
        },
        // 当前页全选时，判断已选数据是否存在，不存在则添加
        handleSelectAll(selection) {
            selection.forEach(item => {
                if (this.selectedRoleGroupData.findIndex(i => i.id === item.id) < 0) {
                    this.selectedRoleGroupData.push(item);
                }
            });
        },
        // 清空所有已选项
        handleClearSelect() {
            this.selectedRoleGroupData = [];
        },
        // 查找单一角色组信息
        handleGetRoleGroup(id) {
            return this.list.find(item => item.id === id);
        },

        // 删除
        handleDelete(id) {
            if (this.loading) return;
            let _this = this;
            this.$Modal.confirm({
                title: this.lang['confirmDelete'],
                cancelText: this.lang['cancel'],
                content: `您确认要删除角色组 <strong>${this.handleGetRoleGroup(id).rolegpName}</strong>？`,
                onOk () {
                    _this.deleteRoleGroup(id);
                }
            })
        },
        //根据职位ID删除职位
        deleteRoleGroup(id) {
            this.$api.RoleGroup.deleteById(id).then(res => {
                this.submitting = false;
                this.drawer.show = false;
                this.$Modal.remove();
                this.handleClearSelect();
                this.handleChangePage(1);
            })
        },

        // 批量删除
        handleDeleteMultiple() {
            if (this.loading) return;
            const ids = this.selectedRoleGroupData.map(item => item.id);
            const names = this.selectedRoleGroupData.map(item => item.rolegpName);
            let _this = this;
            this.$Modal.confirm({
                title: this.lang['confirmDelete'],
                cancelText: this.lang['cancel'],
                content: `您确认要删除角色组 <strong>${names}</strong>？`,
                onOk () {
                    _this.deleteRoleGroupMultiple(ids);
                }
            })
        },

        //批量删除
        deleteRoleGroupMultiple(ids) {
            this.$api.RoleGroup.deleteByIds(ids).then(res => {
                this.submitting = false;
                this.drawer.show = false;
                this.$Modal.remove();
                this.handleClearSelect();
                this.handleChangePage(1);
            })
        },
        // 编辑
        handleEdit(id) {
            this.roleGroupInfo = cloneDeep(this.handleGetRoleGroup(id));
            this.roleGroupInfoString = JSON.stringify(this.roleGroupInfo);
            this.drawer.type = 'edit';
            this.drawer.show = true;
            this.handleInitRoleGroupInfoForm();
        },
        handleInitRoleGroupInfoForm() {
            this.roleGroupInfoReady = false;
            this.$nextTick(() => {
                this.roleGroupInfoReady = true;
            });
        },
        // 关闭编辑
        handleCloseEdit() {
            // 判断内容是否修改，没修改则直接关闭
            if (this.drawer.type === 'edit') {
                const editRoleGroupInfo = cloneDeep(this.roleGroupInfo);
                const editRoleGroupInfoString = JSON.stringify(editRoleGroupInfo);
                if (editRoleGroupInfoString !== this.roleGroupInfoString) {
                    return new Promise((resolve) => {
                        this.$Modal.confirm({
                            title: this.lang['confirm'],
                            cancelText: this.lang['cancel'],
                            content: '您已经修改了角色组信息，是否直接关闭？',
                            onOk: () => {
                                resolve();
                            }
                        });
                    });
                }
            }
        },
        // 添加角色组
        handleOpenCreate() {
            this.roleGroupInfo = {
                id: '',
                rolegpName: '',
                rolegpCode: '',
                rolegpDescrib: '',
                menu_list: []
            };
            this.drawer.type = 'new';
            this.drawer.show = true;
            this.handleInitRoleGroupInfoForm();
        },
        handleSubmitEdit() {
            this.$refs.roleGroupInfoForm.validate(valid => {
                if (valid) {
                    if (this.submitting) return;
                    this.submitting = true;
                    this.$api.RoleGroup.update(this.roleGroupInfo).then(res => {
                        this.submitting = false;
                        this.drawer.show = false;
                        this.handleClearSelect();
                        this.handleChangePage(1);
                    })
                }
            });
        },
        handleSubmitNew() {
            if (this.submitting) return;
            this.$refs.roleGroupInfoForm.validate(valid => {
                if (valid) {
                    if (this.submitting) return;
                    this.submitting = true;
                    this.$api.RoleGroup.add(this.roleGroupInfo).then(res => {
                        this.submitting = false;
                        this.drawer.show = false;
                        this.handleClearSelect();
                        this.handleChangePage(1);
                    })
                }
            });
        },
        // 打开分配权限
        handleOpenRole(id) {
            this.roleGroupInfo = cloneDeep(this.handleGetRoleGroup(id));
            this.roleGroupInfoString = JSON.stringify(this.roleGroupInfo);
            this.selectedRoleIds = [];
            let condition = "rolegpId="+this.roleGroupInfo.id;
            this.$api.RoleGroupRole.query({condition}).then(records => {
                if (records && records.length> 0) {
                    records.map(r=>{
                        this.selectedRoleIds.push(r.roleId)
                    })
                }
                this.$refs.tableRole.selectedRoleData = [];
                this.$refs.tableRole.getData();
                this.modal.show = true;
            })
        },
        handleSubmitPermission() {
            let roleIds = this.$refs.tableRole.selectedRoleData;
            let condition = "rolegpId="+this.roleGroupInfo.id;
            let records = [];
            roleIds.map(roleId=>{
                records.push({rolegpId:this.roleGroupInfo.id,roleId:roleId})
            })
            if (this.submitting) return;
            this.submitting = true;
            this.$api.RoleGroupRole.firstDeleteAndAdd(condition,records).then(res => {
                this.submitting = false;
                this.modal.show = false;
            })
        },
    },
    mounted() {
        this.initElementHeight();
    }
}
</script>
<style lang="less">
.page-sys-role {
    &-drawer {
        &-footer {
            width: 100%;
            position: absolute;
            bottom: 0;
            left: 0;
            border-top: 1px solid #e8e8e8;
            padding: 10px 16px;
            text-align: right;
            background: #fff;
        }
    }
}
</style>
